﻿using Microsoft.Extensions.DependencyInjection;
using Modules.Device.Entitys;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.DBContext;
using PmSoft.Repositories;
using PmSoft.Utilities;

namespace Modules.Device.Repositories
{
    [UseDI(ServiceLifetime.Scoped)]
    public class CheckinDeviceCommandRepository : Repository<CheckinDeviceCommand, DefaultDbContext>
    {
        public CheckinDeviceCommandRepository(DefaultDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
        {
        }

        public IPagedList<CheckinDeviceCommand> GetProjectCheckinDeviceCommands(CheckinDeviceCommandQuery query, int pageIndex, int pageSize)
        {
            Sql sql = Sql.Builder;
            sql.Select("id")
                .From("checkin_device_command");
            sql.Where("device_code=@0", query.DeviceCode);
            if (!string.IsNullOrEmpty(query.Keywords))
                sql.Where("(name Like @0 or device_code Like @0)", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");
            if (query.Status.HasValue) {
                sql.Where("status=@0", query.Status);
            }
            sql.OrderBy("create_time DESC");
            return GetPagingEntities(pageSize, pageIndex, sql);
        }

        public CheckinDeviceCommand? GetProjectCheckinDeviceCommand(string messageId)
        {
            Sql sql = Sql.Builder.Select("id").From("checkin_device_command").Where("messageId=@0", messageId);
            var id = DbContext.FirstOrDefault<int>(sql);
            if (id == 0)
                return null;
            return Get(id);
        }
    }
}